﻿using System;
using System.Collections;
using System.Collections.ObjectModel;
using System.Collections.Specialized;

namespace Iworld.Toolkit.Converter
{
    /// <summary>
    ///  可以访问集合索引的转换器
    /// </summary>
    public class IndexedCollectionConverter : ConverterBase<object, IEnumerable>
    {
        protected override IEnumerable ConvertNotNull(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
             IEnumerable source =  GetSourceEnumerable(value);
             ObservableCollection<IndexedObject> retVal = new ObservableCollection<IndexedObject>();
             if (source is INotifyCollectionChanged)
             {
                 INotifyCollectionChanged iCc = (INotifyCollectionChanged)source;
                 iCc.CollectionChanged += (sender, args) =>
                 {
                     RefreshCollection(source, retVal);
                 };
             }
             RefreshCollection(source, retVal);
             return retVal;
        }

        private void RefreshCollection(IEnumerable source, ObservableCollection<IndexedObject> target)
        {
            target.Clear();
            int i = 0;
            foreach(var k in source)
            {
                IndexedObject io = GetIndexedObject(i, k);
                target.Add(io);
                i++;
            }

        }

        protected virtual IEnumerable GetSourceEnumerable(object value)
        {
            return (IEnumerable)value;
        }
 
        protected virtual IndexedObject GetIndexedObject(int index,object sourceValue)
        {
            return new IndexedObject() { SourceValue = sourceValue,Key = index };
        }

        protected override object ConvertBackNotNull(IEnumerable value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

    public class IndexedObject
    {
        public object Key { set; get; }

        public object SourceValue { set; get; }
    }

 

}

